#include "axistag.h"

AxisTag::AxisTag(QCPAxis *parentAxis) : QObject(parentAxis),
    m_axis(parentAxis)
{
    //对象锚
    //虚拟跟踪器在这里充当一个不可见的锚，它总是粘在rect轴的右侧
    m_dummyTracer = new QCPItemTracer(m_axis->parentPlot());
    m_dummyTracer->setVisible(false);
    m_dummyTracer->position->setTypeX(QCPItemPosition::ptAxisRectRatio);
    m_dummyTracer->position->setTypeY(QCPItemPosition::ptPlotCoords);
    m_dummyTracer->position->setAxisRect(m_axis->axisRect());
    m_dummyTracer->position->setAxes(0, m_axis);
    m_dummyTracer->position->setCoords(1, 0);

    //将箭头末端（头部）设置为与虚拟跟踪器一起移动,方法是将其设置为其父级锚;它的坐标系（setCoords）因此是像素,
    //这就是所需的水平方向实现第二个y轴的标签偏移,这个水平偏移量是动态的;在AxisTag::updatePosition中更新;
    //箭头“start”被简单地设置为以“end”作为父级锚。它被赋予一个向右的水平偏移,这将产生一个15像素长的箭头;
    m_arrow = new QCPItemLine(m_axis->parentPlot());
    m_arrow->setLayer("overlay");
    m_arrow->setClipToAxisRect(false);
    m_arrow->setHead(QCPLineEnding::esSpikeArrow);
    m_arrow->end->setParentAnchor(m_dummyTracer->position);
    m_arrow->start->setParentAnchor(m_arrow->end);
    m_arrow->start->setCoords(15, 0);

    //文本标签锚定在箭头开始（尾部）处，其“位置”与
    //左对齐，并垂直居中于文本标签框。
    m_label = new QCPItemText(m_axis->parentPlot());
    m_label->setLayer("overlay");
    m_label->setClipToAxisRect(false);
    m_label->setPadding(QMargins(3, 0, 3, 0));
    m_label->setBrush(QBrush(Qt::white));
    m_label->setPen(QPen(Qt::blue));
    m_label->setPositionAlignment(Qt::AlignLeft|Qt::AlignVCenter);
    m_label->position->setParentAnchor(m_arrow->start);
}

AxisTag::~AxisTag()
{
    if (m_dummyTracer)
      m_dummyTracer->parentPlot()->removeItem(m_dummyTracer);
    if (m_arrow)
      m_arrow->parentPlot()->removeItem(m_arrow);
    if (m_label)
      m_label->parentPlot()->removeItem(m_label);
}

void AxisTag::setPen(const QPen &pen)
{
    m_arrow->setPen(pen);
    m_label->setPen(pen);
}

void AxisTag::setBrush(const QBrush &brush)
{
    m_label->setBrush(brush);
}

void AxisTag::setText(const QString &text)
{
    m_label->setText(text);
}

void AxisTag::updatePosition(double value)
{
    m_dummyTracer->position->setCoords(1, value);

    m_arrow->end->setCoords(m_axis->offset(), 0);
}
